package com.hmdp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    private  ShopTypeMapper shopTypeMapper;

    @Override
    public List<ShopType> queryList() {
        // 在缓存中查询元素个数，如果大于0，直接返回
        Long cards = stringRedisTemplate.opsForZSet().zCard("shop_type");
        if (cards > 0) {
            Set<String> shopTypeSet = stringRedisTemplate.opsForZSet().range("shop_type", 0, cards - 1);
            ArrayList<ShopType> shopTypes = shopTypeSet.stream().map(item -> {
                        return JSON.parseObject(item, ShopType.class);
                    })
                    // 将set转为list
                    .collect(ArrayList<ShopType>::new, ArrayList::add, ArrayList::addAll);
            return shopTypes;
        }
        // 查询数据库
        QueryWrapper<ShopType> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        List<ShopType> shopTypes = shopTypeMapper.selectList(queryWrapper);
        if(shopTypes == null || shopTypes.size() == 0){
            return null;
        }
        // 将查询到的数据写入缓存
        shopTypes.forEach(shopType -> {
            stringRedisTemplate.opsForZSet().add("shop_type", JSON.toJSONString(shopType), shopType.getSort());
        });
        return shopTypes;
    }
}
